const App = {
  mixins: [Save],//配置文件，路径/utils/mixins.js
  data() {
    return {
      city: [],
      dataForm: {
        Tenure_SerialNumber: '',
      },
      dataForm1: [{
        id: createUniqueString(),
        Party_Position: '',
        Position_Number: 1,
      }],
      village_position: [],
      tenure_position: [],
      count: {},
      TenureData: []
    };
  },
  mounted() {
    this.getCategory();
    if (this.action == 'Modify') {
      this.getPosition();
    }
  },
  methods: {
    End_Date_Validity(rule, value, callback) {
      if (!value) {
        callback(new Error('任期结束时间'));
      } else if ((+new Date(value)) < (+new Date(this.dataForm.Start_Date))) {
        callback(new Error("任期结束时间不能小于任期开始时间"));
      } else {
        callback();
      }
    },
    getPosition() {
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        type: "POST",
        data: {
          Data: 'village_tenure_position',
          Condition: "Tenure_SerialNumber='" + this.nodeKey + "'",
        },
        success: (data) => {
          data.forEach(item => {
            item.id = item.Tenure_Position_SerialNumber;
            item.Position_Number = 1;
            if (!this.count[item.Village_Position_SerialNumber]) {
              this.count[item.Village_Position_SerialNumber] = 1;
            }
            this.count[item.Village_Position_SerialNumber]++;
          })
          this.tenure_position = data;
          console.log(this.tenure_position);
          this.dataForm1 = this.convertToTree(data.filter(i => i.Row_Status != '1'));
        },
        complete: (XMLHttpRequest) => {

          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    convertToTree(items) {
      const result = []; // 存储最终的树形结构
      const itemMap = {}; // 用于快速查找项目
      // 首先将所有项目存储在 itemMap 中
      items.forEach(item => {
        itemMap[item.id] = { ...item, children: [] };
      });
      // 遍历所有项目，构建树形结构
      items.forEach(item => {
        const { Tenure_Position_SerialNumber, Parent_SerialNumber } = item;
        const treeItem = itemMap[Tenure_Position_SerialNumber];

        if (Parent_SerialNumber == '') {
          // 如果没有父级 ID，说明是根节点
          result.push(treeItem);
        } else {
          // 如果有父级 ID，将当前节点添加到父节点的 children 中
          if (itemMap[Parent_SerialNumber]) {
            itemMap[Parent_SerialNumber].children.push(treeItem);
          }
        }
      });
      return result;
    },
    changeOrganization(val) {
      this.dataForm.Start_Date = ''
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableName`,
        type: "POST",
        data: {
          Data: 'village_organization_tenure',
          Condition: "Row_Status='0' AND VillageNumber='" + this.dataForm.VillageNumber + "'"
            + "ORDER BY Tenure_SerialNumber DESC\r\n",
        },
        success: (data) => {
          this.TenureData = data;
          this.dataForm.Tenure = '第' + this.numberToChinese(Number(data.length) + 1) + '任'
          if (data.length > 0) {
            this.dataForm.Start_Date = getYMDDate(+new Date(data[0].End_Date) + 24 * 3600 * 1000);
          }
        },
        complete: (XMLHttpRequest) => {

          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    getCategory() {
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/clientOperation/getDistrictTree`,
        type: "GET",
        data: {
          DistrictCode: '232723'
        },
        success: (data) => {
          this.city = data; // 直接使用 this
        },
        complete: (XMLHttpRequest) => {

          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableName`,
        type: "POST",
        data: {
          Data: 'village_position',
          Condition: "Row_Status='0'",
        },
        success: (data) => {
          this.village_position = data; // 直接使用 this
        },
        complete: (XMLHttpRequest) => {

          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    configSubmit(arr, id, village_tenure_position) {
      let Parent_SerialNumber = id;
      let str;
      if (this.action == 'Add') {
        str = this.dataForm.VillageNumber + '-' + (this.TenureData.length + 1);
      } else if (this.action == 'Modify') {
        str = this.dataForm.VillageNumber + '-' + this.chineseToArabic(this.dataForm.Tenure[1]);
      }

      arr.forEach(item => {
        for (let i = 1; i <= item.Position_Number; i++) {
          if (!this.count[item.Village_Position_SerialNumber]) {
            this.count[item.Village_Position_SerialNumber] = 1;
          }
          let Tenure_Position_SerialNumber;
          if (this.action == 'Modify' && item.Tenure_Position_SerialNumber) {
            Tenure_Position_SerialNumber = item.Tenure_Position_SerialNumber
          } else {
            Tenure_Position_SerialNumber = str + '-' + item.Village_Position_SerialNumber + '-' + this.count[item.Village_Position_SerialNumber];
            this.count[item.Village_Position_SerialNumber]++;
          }
          village_tenure_position.push({
            Tenure_Position_SerialNumber,
            Tenure_SerialNumber: this.dataForm.Tenure_SerialNumber,
            Village_Position_SerialNumber: item.Village_Position_SerialNumber,
            Parent_SerialNumber,
          })
          if (item.children) {
            this.configSubmit(item.children, Tenure_Position_SerialNumber, village_tenure_position);
          }
        }
      })
    },
    async handleSubmit() {
      const allValid = await this.validateAllForms();
      if (allValid) {
        this.loading = true;

        let village_tenure_position = [];
        this.configSubmit(this.dataForm1, '', village_tenure_position);

        let ls_URL = window.location.href;
        const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
        let lJSONObject_Data_Options = new Object();
        lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

        let ls_MainTableName = lJSONObject_Data_Options.TableName;
        let ls_DataForm = lJSONObject_Data_Options.form;
        let ls_primary_key = lJSONObject_Data_Options.primary_key;
        //没有子表下面内容就会报错，try/catch抛出异常
        try {
          //可能涉及多个子表
          document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
            let lJSONObject_ChildData_Options = new Object();
            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
            if (this[ls_DataForm][ls_primary_key]) {
              this[ls_ChildDataForm].forEach(item => {
                item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
              })
            }
            //建立子表结构体
            let JSONArray_ChildRecord = new Array();
            JSONArray_ChildRecord = this[ls_ChildDataForm];
            if (!this[ls_DataForm].Children) {
              this[ls_DataForm].Children = new Object();
            }
            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
          })
        } catch (error) {

        }
        //建立新增提交结构
        let lJSONObject_DataSet = new Object();
        if (action == 'Add') {
          if (this.nodeKey) {
            this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
          }
          this[ls_DataForm]['Children'] = {
            village_tenure_position
          }

          let lJSONArray_Record = new Array();
          lJSONArray_Record.push(this[ls_DataForm]);
          let lJSONObject_Table = new Object();
          lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
          lJSONObject_DataSet[action] = lJSONObject_Table;
        } else if (action == 'Modify') {
          let tenure_position = this.tenure_position;
          tenure_position.forEach(item => {
            let obj = village_tenure_position.filter(i => i.Tenure_Position_SerialNumber == item.Tenure_Position_SerialNumber)[0];
            if (obj) {
              item.Village_Position_SerialNumber = obj.Village_Position_SerialNumber;
            } else {
              item.Row_Status = '1';
            }
          })

          village_tenure_position.forEach(item => {
            let obj = tenure_position.filter(i => i.Tenure_Position_SerialNumber == item.Tenure_Position_SerialNumber)[0]
            if (!obj) {
              tenure_position.push(item);
            }
          })

          this[ls_DataForm].Children = {
            village_tenure_position: tenure_position
          }

          const { add, modify } = this.deal(this[ls_DataForm]);
          let lJSONArray_Record = new Array();
          lJSONArray_Record.push(modify);

          let lJSONObject_Table = new Object();
          lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

          lJSONObject_DataSet[action] = lJSONObject_Table;
          lJSONObject_DataSet['Add'] = new Object();
          if (add != null) {
            let lJSONArray_Record_Add = new Array();
            lJSONArray_Record_Add.push(add);

            let lJSONObject_Table_Add = new Object();
            lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

            lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
          }

        }
        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
        if (!lJSONObject_DataSet['Add']) {
          lJSONObject_DataSet['Add'] = new Object();
        }
        lJSONObject_DataSet['Add']['base_operation_log'] = [{
          Operation_Type: '0',
          Operation_Path: this.relativePath,
          Operation_Main,
          Operation_Interface: "generalSave",
          Operation_IP: getIpAddress()
        }]
        submitSave(lJSONObject_DataSet, (res) => {
          if (res.Status == 'success') {
            window.location.href = './index.html'
            // window.history.go(-1);
          }
          this.loading = false;
        })
        // $.ajax({
        //   headers: requestHeaders(),
        //   url: `${mh}/generalBusiness/generalSave`,
        //   method: "post",
        //   data: {
        //     Data: JSON.stringify(lJSONObject_DataSet),
        //   },
        //   success: (res) => {
        //     if (res.Status == 'success') {
        //       window.location.href = './index.html'
        //       // window.history.go(-1);
        //     }
        //   },
        //   complete: (XMLHttpRequest) => {
        //     this.loading = false;
        //     requestPretreatment(XMLHttpRequest);
        //   },
        // });
      }
    },
    handleAdd(row) {
      let obj = {
        id: createUniqueString(),
        Party_Position: '',
        Position_Number: 1,
      }
      if (row) {
        if (!row.children) {
          row.children = [];
        }
        row.children.push(obj);
      } else {
        this.dataForm1.push(obj);
      }
    },
    handleRemove(row) {
      this.dataForm1 = this.dataForm1.filter(i => i.id != row.id);
      this.configRemove(this.dataForm1, row);
    },
    configRemove(arr, row) {
      arr.forEach(item => {
        if (item.children) {
          item.children = item.children.filter(i => i.id != row.id);
          this.configRemove(item.children, row);
        }
      })
    }
  },
};

const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
app.component('yl-cascader', ylCascader)
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
